<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'

interface ChatHistory {
  conversationId: number
  userId: number
  title: string
  startTime: string
  image: string
  description: string
  lastMessage: string
}

const router = useRouter()
const route = useRoute()
const isVisible = ref(false)
const showGreeting = ref(false) // 确保 showGreeting 已经定义

// 定义 chatHistories 为响应式变量
const chatHistories = ref<ChatHistory[]>([])

// 定义 Token 类型为 string | null
let Token: string | null = "";

const getToken = () => {
  Token = sessionStorage.getItem("phone") || ""; // 如果获取不到则赋值为空字符串
}

// 确保在组件挂载时获取 Token
onMounted(() => {
  // 判断是否从其他页面跳转过来，这里假设从其他页面跳转过来时会带有from参数
  if (route.query.from) {
    showGreeting.value = true;
  }
  getToken(); // 确保在组件挂载时获取 Token
  fetchChatHistories(); // 调用 fetchChatHistories 获取聊天记录
});

// 创建 axios 实例
const apiClient = axios.create({
  baseURL: '/api',
});

// 添加请求拦截器
apiClient.interceptors.request.use(
  config => {
    if (Token) {
      config.headers['Token'] = `${Token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
apiClient.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    console.error('请求失败:', error);
    throw error;
  }
);

const fetchChatHistories = async () => {
  try {
    const response = await apiClient.get('/dialogue/dialogue/getHistoryMessage'); // 使用 apiClient 进行请求
    const data = response.data.data;
    console.log('聊天记录:', data);
    chatHistories.value = data; // 将查询结果赋值给 chatHistories
  } catch (error) {
    console.error('There was a problem with the fetch operation:', error);
  }
}

const goBack = () => {
  isVisible.value = false
  setTimeout(() => {
    router.back()
  }, 300) // 等待动画完成后返回
}

const deleteChat = async (conversationId: number) => {
  // 添加确认提示
  const confirmDelete = window.confirm("您确定要删除这条聊天记录吗？");
  if (!confirmDelete) {
    return; // 如果用户选择取消，直接返回
  }

  try {
    // 发送 DELETE 请求到后端
    await apiClient.delete(`/dialogue/dialogue/deleteChat/${conversationId}`); // 假设后端接口为这个路径
    
    console.log(`聊天记录 ${conversationId} 已删除`);
  } catch (error) {
    console.error('删除聊天记录失败:', error);
  }
}

// 新增对话
const addNewChat = () => {
  router.push('/index')
}

// 根据 conversationId 找到对应的聊天记录并导航到详情页面
const findById = (conversationId: number) => {
  const chat = chatHistories.value.find(chat => chat.conversationId === conversationId);
  if (chat) {
    router.push({ path: '/chat-detail', query: { id: conversationId } });
  } else {
    console.error('未找到对应的聊天记录');
  }
}

onMounted(() => {
  // 添加一个小延迟来触发进入动画
  setTimeout(() => {
    isVisible.value = true
  }, 50)
})
</script>

<template>
  <div class="history-chat" :class="{ visible: isVisible }">
    <!-- 顶部导航栏 -->
    <div class="nav-bar">
      <div class="nav-left">
        <div class="back-btn" @click="goBack">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
            <path fill="currentColor" d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
          </svg>
        </div>
        <div class="title">历史对话</div>
      </div>
      <div class="nav-right">
        <svg class="delete-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
          <path fill="currentColor" d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
        </svg>
      </div>
    </div>

    <!-- 聊天历史列表 -->
    <div class="chat-list">
      <div
        v-for="chat in chatHistories"
        :key="chat.conversationId"
        class="chat-item" @click="findById(chat.conversationId)"
      >
        <div class="chat-content">
          <div class="chat-avatar">
            <img v-if="chat.image" :src="chat.image" alt="avatar" />
            <img v-else src="default-avatar.png" alt="默认头像" />
          </div>
          <div class="chat-info">
            <div class="chat-header">
              <span class="chat-title">{{ chat.title }}</span>
              <span class="chat-time">{{ chat.startTime }}</span>
            </div>
            <div class="chat-message">{{ chat.lastMessage }}</div>
          </div>
        </div>
        <div class="delete-btn" @click="deleteChat(chat.conversationId)">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
            <path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
          </svg>
        </div>
      </div>
    </div>

    <!-- 新增对话按钮 -->
    <div class="add-chat-button" @click="addNewChat">
      <div class="button-content">
        <svg class="plus-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
          <path fill="currentColor" d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
        </svg>
        <span>新增对话</span>
      </div>
    </div>
  </div>
</template>

<style scoped>
.history-chat {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #000;
  transform: translateX(-100%);
  transition: transform 0.3s ease-out;
  z-index: 1000;
}

.history-chat.visible {
  transform: translateX(0);
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #1a1a1a;
  color: white;
}

.nav-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-btn {
  width: 24px;
  height: 24px;
  cursor: pointer;
}

.title {
  font-size: 17px;
  font-weight: 500;
}

.delete-icon {
  width: 24px;
  height: 24px;
  cursor: pointer;
}

.chat-list {
  padding: 12px;
  padding-bottom: 80px; /* 为底部按钮留出空间 */
  overflow-y: auto; /* 允许垂直滚动 */
  max-height: calc(100% - 80px); /* 限制最大高度，留出空间给底部按钮 */
}

.chat-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  margin-bottom: 8px;
  background: #1a1a1a;
  border-radius: 8px;
  color: white;
}

.chat-content {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.chat-avatar {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  overflow: hidden;
  background: #333;
}

.chat-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.chat-info {
  flex: 1;
  min-width: 0;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.chat-title {
  font-size: 15px;
  font-weight: 500;
  color: #fff;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-time {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
  margin-left: 8px;
}

.chat-message {
  font-size: 13px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.delete-btn {
  width: 24px;
  height: 24px;
  margin-left: 12px;
  cursor: pointer;
  color: #666;
}

.delete-btn:hover {
  color: #ff4d4f;
}

.add-chat-button {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: #007AFF;
  color: white;
  padding: 12px 24px;
  border-radius: 24px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: transform 0.2s, box-shadow 0.2s;
  z-index: 100;
}

.add-chat-button:hover {
  transform: translateX(-50%) translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.add-chat-button:active {
  transform: translateX(-50%) translateY(0);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.button-content {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  font-weight: 500;
}

.plus-icon {
  width: 20px;
  height: 20px;
}
</style>